<?php

$server = new Swoole\WebSocket\Server("0.0.0.0", 10009);

/**
 * 当WebSocket客户端与服务器建立连接并完成握手后会回调此函数
 */
$server->on('open', function (Swoole\WebSocket\Server $server, Swoole\Http\Request $request) {
    echo "有新连接".$request->fd.PHP_EOL;
    $server->push($request->fd, "hello client".PHP_EOL);
});

/**
 * 当服务器收到来自客户端的数据帧时会回调此函数  此回调方法不能缺少
 */
$server->on('message', function (Swoole\WebSocket\Server $server, swoole_websocket_frame  $frame) {
    echo "新消息: ".$frame->data.PHP_EOL;
    $server->push($frame->fd, "this is server");
});

/**
 * 客户端关闭连接时触发此回调函数
 */
$server->on('close', function ($ser, $fd) {
    echo "client {$fd} closed\n";
});

/**
 * 启动服务
 */
$server->start();

